<?php

namespace App\Http\Controllers\Api;

use App\Models\AnswerModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AnswerController extends Controller
{
    public function index(Request $request)
    {
        $rs = AnswerModel::wherein('tid',[3,4])->get();
        if(!empty($rs[0]->id)){
            foreach ($rs as &$vo)
            {
                if($vo['tid'] == 3){
                    $arr['most'][] = [
                        'title'=>$vo['name'],
                        'value'=>$vo['specify']
                    ];
                }
                if($vo['tid'] == 4){
                    $arr['like'][] = [
                        'title'=>$vo['name'],
                        'value'=>$vo['specify']
                    ];
                }
            }
			$arr['audio'] = '/mp3/just_the_way_you_are.mp3';
            return [
                'code'=>200,
                'data'=>$arr,
                'message'=>'成功！'
            ];
        }else{
            return $this->error($rs);
        }
    }
    protected function error($arr = '',$ny = '请传正确的参数或值')
    {
        return [
            'code'=>500,
            'data'=>$arr,
            'message'=>$ny
        ];
    }
	public function uploadimg(Request $request){
		// $params['uid']  = '123456';
		$file = $request->base64;
		$uid = abs(intval(1234567));//1234567
		$uid = sprintf("%09d", $uid);
		$dir1 = substr($uid, 0, 3);//一级目录
		$dir2 = substr($uid, 3, 2);//二级目录
		$dir3 = substr($uid, 5, 2);//三级目录

		$path = 'upload/newheadimg/';
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file, $result)){
			$type = $result[2];
			$new_file = 'base64/'.$dir1.'/'.$dir2.'/'.$dir3.'/';
			$array_dir=explode("/",$new_file);//把多级目录分别放到数组中
			for($i=0;$i<count($array_dir);$i++) {
				$path .= $array_dir[$i] . "/";
				if (!file_exists($path)) {
					mkdir($path, 0700);
				}
			}
			$new_file = $path.substr($uid, -2).'_avatar_small'.".{$type}";
			if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $file)))){
				/*这里是数据库操作*/
				return $new_file;
			}else{
				return false;
			}
		}else{
			return false;
	}}

}
